package com.qyc.Microservice.interceptor;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import com.qyc.Microservice.dto.result.ResponseResult;

/**
 * 获取此请求，是否需要返回值包装，设置一个属性标记。
 * 
 * @author dell
 *
 */
@Component
public class ResponseResultInterceptor implements HandlerInterceptor {

	
	//标记名称
	public static final String RESPONSE_RESULT_ANN = "RESPONSE_RESULT_ANN";

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		
		//请求的方法
		if(handler instanceof HandlerMethod) {
			final HandlerMethod handlerMethod = (HandlerMethod) handler;
			final Class<?> clazz = handlerMethod.getBeanType();
			final Method method = handlerMethod.getMethod();
			//判断是否在对象上加了注解
			if(clazz.isAnnotationPresent(ResponseResult.class)) {
				//设置此请求返回体，需要包装，往下传递，在ResponseBodyAdvice接口进行判断
				request.setAttribute(RESPONSE_RESULT_ANN, clazz.getAnnotation(ResponseResult.class));
			}else if(method.isAnnotationPresent(ResponseResult.class)) {//判断方法是否有注解
				//设置此请求返回体，需要包装，往下传递，在ResponseBodyAdvice接口进行判断
				request.setAttribute(RESPONSE_RESULT_ANN, method.getAnnotation(ResponseResult.class));
			}
		}
		return HandlerInterceptor.super.preHandle(request, response, handler);
	}
}
